﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DefeatEpidemic.Common;
using DefeatEpidemic.Models;
using DefeatEpidemic.RequestModels;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DefeatEpidemic.API
{
    [Route("api/[controller]/[action]")]
    [GlobalActionFilter]
    public class ApplicationController : Controller
    {
        private readonly DefeatEpidemicContext _context;

        public ApplicationController(DefeatEpidemicContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取出行记录(返回值中的status，0-代表未审核，1-代表审核通过，2-代表2次审核通过（即进审核和出审核），-1表示未通过)
        /// </summary>
        /// <param name="member_id"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public Response GetRecordList(Guid member_id, int pageindex = 1, int pagesize = 10)
        {
            Response resp = new Response();
            try
            {
                int skip = (pageindex - 1) * pagesize;
                int total = _context.Applications.Where(u => u.member.id == member_id).Count();
                var apps = _context.Applications.Where(u => u.member.id == member_id)
                    .OrderByDescending(u=>u.created_at)
                    .Skip(skip)
                    .Take(pagesize)                    
                    .AsQueryable();

                resp.code = 1;
                resp.data = new { total, items = apps };
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message}.{ex.StackTrace}";
            }
            return resp;
        }

        /// <summary>
        /// 提交申请
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response> Apply([FromBody] ApplyModel model)
        {
            Response resp = new Response();
            try
            {
                if (ModelState.IsValid)
                {
                    //未审核的数量
                    int uncount = _context.Applications.Count(u => u.member.id == model.member_id && u.status < 2);
                    if (uncount > 0)
                    {
                        resp.code = -1;
                        resp.message = "存在未审核的申请";
                    }
                    else
                    {
                        var member = await _context.Members.FindAsync(model.member_id);
                        Guid app_id = Guid.NewGuid();
                        var application = new Application()
                        {
                            id = app_id,
                            applicant = member.name,
                            connect = member.mobile,
                            from = member.address,
                            to = model.target,
                            selfTemp = model.temp,
                            reason = model.reason,
                            isDirve = model.isDirve,
                            member = member
                        };
                        if (model.isDirve == 1 && !string.IsNullOrEmpty(member.carNumber))
                            application.carNumber = member.carNumber;
                        _context.Add(application);
                        int ret = await _context.SaveChangesAsync();
                        if (ret > 0)
                        {
                            string url = Common.WinxinHelper.GetWxShareCode(app_id.ToString("N"), "pages/admindengji/index", 200, app_id.ToString("N") + ".jpg");
                            resp.code = 1;
                            resp.message = "success";
                            resp.data = new { url };
                            string open_id = model.open_id;
                            if (string.IsNullOrEmpty(open_id))
                            {
                                var oauth = _context.Wxoauths.Where(u => u.member.id == model.member_id).FirstOrDefault();
                                open_id = oauth.open_id;
                            }
                            await Task.Run(() => WinxinHelper.PushMessageAsync(open_id, $"{member.name}申请离开社区", "审核中", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "请在离开社区时将申请码出示给物管人员"));
                        }
                    }
                }
                else
                {
                    resp.code = -1;
                    resp.message = "提交的参数模型不规范";
                }
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message},{ex.StackTrace}";
            }
            return resp;
        }

        /// <summary>
        /// 获取最近的申请
        /// </summary>
        /// <param name="member_id"></param>
        /// <returns></returns>
        [HttpGet]
        public Response GetLastApplication(Guid member_id)
        {
            Response resp = new Response();
            try
            {
                var application = _context.Applications
                    .Where(u => u.member.id == member_id && u.status < 2)
                    .OrderByDescending(u => u.created_at)
                    .FirstOrDefault();
                if (application != null)
                {
                    resp.code = 1;
                    resp.data = new { application };
                }
                else
                {
                    resp.code = 0;
                    resp.message = "暂无登记记录";
                }
            }
            catch(Exception ex)
            {
                resp.code = -1;
                resp.message = $"error:{ex.Message}";
            }
            return resp;
        }
        /// <summary>
        /// 获取最近一次申请详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response> GetApplication(string guid)
        {
            Response resp = new Response();
            try
            {
                Guid app_id;
                if (Guid.TryParseExact(guid, "N", out app_id))
                {
                    var app = await _context.Applications.FindAsync(app_id);
                    if (app != null)
                    {                        
                        resp.code = 1;
                        resp.data = new { app };
                    }
                }
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error,{ex.Message},{ex.StackTrace}";
            }
            return resp;
        }

        /// <summary>
        /// 审批申请
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response> CheckApplication([FromBody] RequestModels.CheckModel model)
        {
            Response resp = new Response() { message = "failed" };
            try
            {
                var app = await _context.Applications.FindAsync(model.app_id);                
                if (app.status == 2)
                {
                    resp.message = "该申请已结束";
                    return resp;
                }
                string message = "";
                if (app.status == 0)
                {
                    app.status = model.status;
                    message = "出门审核成功";                    
                }
                else if (app.status == 1 && model.status == 1)
                {
                    app.status = 2;
                    message = "进门审核成功";                    
                }
                else
                {
                    app.status = model.status;                   
                }
                app.measuredTemp = model.temp;
                app.remark = model.remark;
                app.outTime = DateTime.Now;
                if (model.temp > 37.5)
                    message = "体温异常";
                app.checker_id = model.checker_id;//这一步考虑欠妥，无所谓了
                var checker = await _context.Members.FindAsync(model.checker_id);
                var checkRecord = new CheckRecord()
                {
                    application = app,
                    checker = checker,
                };
                _context.Add(checkRecord);                
                _context.Update(app);
                int ret = await _context.SaveChangesAsync();
                if (ret > 0)
                {
                    resp.code = 1;
                    resp.message = message;                   
                }
            }
            catch (Exception ex)
            {
                resp.code = -1;
                resp.message = $"error,{ex.Message}";
            }
            return resp;
        }
    }
}
